package com.dashu.school.service;

import com.dashu.base.enums.ReplRyCode;
import com.dashu.base.enums.school.TeacherIidentityType;
import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.UIDUtil;
import com.dashu.base.utils.VerificationUtil;
import com.dashu.school.dto.TeacherClsDTO;
import com.dashu.school.dto.TeacherClsListDTO;
import com.dashu.school.dto.company.CompanyClsDTO;
import com.dashu.school.dto.company.CompanyDTO;
import com.dashu.school.dto.company.CompanyDepartmentDTO;
import com.dashu.school.handler.VerificationException;
import com.dashu.school.model.QTeacherCls;
import com.dashu.school.model.TeacherCls;
import com.dashu.school.result.PageEnty;
import com.dashu.school.vo.TeacherClsListVO;
import com.dashu.school.vo.TeacherClsVO;
import com.dashu.school.vo.UpTeacherClsVO;
import com.dashu.school.vo.UpdateEntityVO;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.FlushModeType;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class TeacherClsService extends DataService {
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CompanyPersonalService companyPersonalService;
    @Autowired
    private CompanyClsService companyClsService;
    @Autowired
    private CompanyDepartmentService companyDepartmentService;

    @Transactional
    public TeacherClsDTO add(TeacherClsVO teacherClsVO) {
        TeacherCls teacherCls = CopyUtil.copyEnty(teacherClsVO, TeacherCls.class);
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            teacherCls.setId(UIDUtil.nextId());
            teacherCls.setCreateUser(userId);
            teacherCls.setCreateTime(System.currentTimeMillis());
            teacherCls.setBindCls(teacherClsVO.getBindCls());
            teacherCls.setBindTeacher(teacherClsVO.getBindTeacher());
            teacherCls.setCompanyId(teacherClsVO.getCompanyId());
            teacherCls.setIdentity(TeacherIidentityType.map.get(teacherClsVO.getIdentity()));
            entityManager.persist(teacherCls);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        TeacherClsDTO teacherClsDTO = CopyUtil.copyEnty(teacherCls, TeacherClsDTO.class);
        return teacherClsDTO;
    }

    @Transactional
    public boolean deleteByTeacherClsId(long teacherClsId) {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qTeacherCls.id.eq(teacherClsId));
        TeacherCls teacherCls;
        queryFactory.select();
        teacherCls = queryFactory
                .select(qTeacherCls)
                .from(qTeacherCls)
                .where(booleanBuilder.getValue()).fetchOne();
        entityManager.remove(teacherCls);
//            entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);

        return true;

    }


    @Transactional
    public TeacherClsDTO updataByTeacherClsId(UpdateEntityVO<UpTeacherClsVO> updateEntityVO) throws Exception {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        UpTeacherClsVO teacherClsVO = updateEntityVO.getEntityVO();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qTeacherCls.id.eq(updateEntityVO.getId()));
        TeacherCls teacherCls;
        try {
            teacherCls = queryFactory
                    .select(qTeacherCls)
                    .from(qTeacherCls)
                    .where(booleanBuilder.getValue()).fetchOne();
            if (teacherCls == null)
                throw new VerificationException(ReplRyCode.RELATION_NOT, ReplRyCode.RELATION_NOT.getMessage());
            teacherCls.setBindCls(teacherClsVO.getBindCls());
            teacherCls.setIdentity(TeacherIidentityType.map.get(teacherClsVO.getIdentity()));
            teacherCls.setUpdateTime(new Date().getTime());
            teacherCls.setUpdateUser(userId);
            teacherCls = entityManager.merge(teacherCls);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
//        entityManager.flush();
        entityManager.setFlushMode(FlushModeType.AUTO);
        TeacherClsDTO teacherClsDTO = CopyUtil.copyEnty(teacherCls, TeacherClsDTO.class);
        return teacherClsDTO;

    }


    public long teacherClsCount(PageEnty<TeacherClsListVO> teacherClsPageEntyVO) throws Exception {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        List<TeacherClsListDTO> teacherClsDTOS = Lists.newArrayList();
        TeacherClsListVO teacherClsVO = teacherClsPageEntyVO.getVo();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qTeacherCls.bindTeacher.eq(teacherClsVO.getBindTeacher()));
        List<TeacherCls> teacherCls = queryFactory
                .select(qTeacherCls)
                .from(qTeacherCls)
                .where(booleanBuilder.getValue())
                .offset((teacherClsPageEntyVO.getPage() - 1) * teacherClsPageEntyVO.getNum())
                .limit(teacherClsPageEntyVO.getNum())
                .orderBy(qTeacherCls.createTime.desc())
                .fetch();
        return teacherCls.size();
    }


    public List<TeacherClsListDTO> pageTeacherList(PageEnty<TeacherClsListVO> teacherClsPageEntyVO) throws Exception {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        List<TeacherClsListDTO> teacherClsDTOS = Lists.newArrayList();
        TeacherClsListVO teacherClsVO = teacherClsPageEntyVO.getVo();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qTeacherCls.bindTeacher.eq(teacherClsVO.getBindTeacher()));
        List<TeacherCls> teacherCls = queryFactory
                .select(qTeacherCls)
                .from(qTeacherCls)
                .where(booleanBuilder.getValue())
                .offset((teacherClsPageEntyVO.getPage() - 1) * teacherClsPageEntyVO.getNum())
                .limit(teacherClsPageEntyVO.getNum())
                .orderBy(qTeacherCls.createTime.desc())
                .fetch();
        teacherCls.stream().forEach(tc -> {
            TeacherClsListDTO teacherClsListDTO = CopyUtil.copyEnty(tc, TeacherClsListDTO.class);
            if (tc.getBindCls() != 0) {
                CompanyDTO companyDTO = companyService.findByCompanyId(tc.getCompanyId());
                teacherClsListDTO.setCompanyName(companyDTO.getCompanyName());
                CompanyClsDTO companyClsDTO = companyClsService.findByCompanyClsId(tc.getBindCls());
                teacherClsListDTO.setBindClsName(companyClsDTO.getClsName());
                teacherClsListDTO.setDepartmentId(companyClsDTO.getDepartmentId());
                teacherClsListDTO.setClsId(companyClsDTO.getId());
                CompanyDepartmentDTO companyDepartmentDTO = companyDepartmentService.findByCompanyDepartmentId(companyClsDTO.getDepartmentId());
                teacherClsListDTO.setDepartmentName(companyDepartmentDTO.getGradeName());
                teacherClsListDTO.setIdentity(tc.getIdentity().name);
                teacherClsDTOS.add(teacherClsListDTO);
            }
        });
        return teacherClsDTOS;
    }


    public TeacherCls existTeacherClsIden(long bindCls, String identity) {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qTeacherCls.bindCls.eq(bindCls));
        booleanBuilder.and(qTeacherCls.identity.eq(TeacherIidentityType.map.get(identity)));
        TeacherCls relationship = queryFactory
                .select(qTeacherCls)
                .from(qTeacherCls)
                .where(booleanBuilder.getValue())
                .fetchOne();
        return relationship;
    }


    public List<TeacherCls> teacherClsList(long bindTeacher, long bindCls) {
        QTeacherCls qTeacherCls = QTeacherCls.teacherCls;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        if (bindCls != 0)
            booleanBuilder.and(qTeacherCls.bindCls.eq(bindCls));
        if (bindTeacher != 0)
            booleanBuilder.and(qTeacherCls.bindTeacher.eq(bindTeacher));
        List<TeacherCls> teacherCls = queryFactory
                .select(qTeacherCls)
                .from(qTeacherCls)
                .where(booleanBuilder.getValue())
                .fetch();
         return teacherCls;
    }


}
